package jsp.servlet;

import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.Employee;
import jsp.classes.Session;

/**
 * @author Remco Haszing
 */
public class UpdateProfile extends HttpServlet {

    /**
     * Updates the user's personal data according to the data in the request
     * parameter. This method updates the user's properties and merges them into
     * the database.
     *
     * @param request The request that should be handled.
     * @param response Unused.
     * @throws IOException  
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Session session = (Session) request.getSession(true).getAttribute("user");
            Employee e = session.getEmployee();
            for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                String k = entry.getKey();
                String[] v = entry.getValue();
                if (k.equals("lastname")) {
                    e.setLastName(v[0]);
                } else if (k.equals("username")) {
                    e.setUserName(v[0]);
                } else if (k.equals("town")) {
                    e.setTown(v[0]);
                } else if (k.equals("postalcode")) {
                    e.setPostalCode(v[0]);
                } else if (k.equals("country")) {
                    e.setCountry(v[0]);
                } else if (k.equals("phonenumber")) {
                    e.setPhoneNumbers(v);
                } else if (k.equals("emailaddress")) {
                    e.setEmailAddresses(v);
                } else if (k.equals("webaddress")) {
                    e.setWebAddresses(v);
                } else if (k.equals("password") && e.validatePassword(request.getParameter("oldpassword")) && v[0].equals(v[1])) {
                    e.setPassword(v[0]);
                }
            }
            session.getJPAConnection().edit(e);
            response.getWriter().print("true");
        } catch (Exception e) {
            response.getWriter().print("false");
        }
    }
}
